﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SWEN3Application.Classes;
using System.Net;
using System.IO;
using System.Globalization;
using System.Text.RegularExpressions;

namespace SWEN3Application
{
    public partial class CheckOut : MasterForm
    {
        private Rooms r;
        private BookingList b;
        private Invoice i = new Invoice();
        private Boolean isValid = true;

        public CheckOut()
        {
            InitializeComponent();
            ExpiryDate.MinDate = DateTime.Now;
        }

        private void CheckOutBtn_Click(object sender, EventArgs e)
        {
            try
            {
                isValid = true;
                errorProvider.Clear();
                if (CreditCardCheckBox.Checked)
                {
                    CustomValidateForCreditCard();
                }
                else
                {
                    isValid = true;
                }
                if (CurrencyRates.Text == "0")
                {
                    isValid = false;
                    errorProvider.SetError(CurrencyRatesTb, "Currency code not found!");
                }
                if (isValid)
                {
                    if (CreditCardCheckBox.Checked)
                    {
                        i.SecurityCode = Convert.ToInt32(SecurityCode.Text);
                        i.ExpiryDate = Convert.ToDateTime(ExpiryDate.Text);
                    }
                    else
                    {
                        i.ExpiryDate = DateTime.MinValue;
                    }
                    i.CreditCardNo = CreditCardNo.Text;
                    i.CardType = CardType.Text;

                    int InvoiceId = InvoiceDBManager.GenerateInvoice(i);
                    if (InvoiceId > 0)
                    {
                        i.InvoiceId = InvoiceId;
                        this.b = BookingDBManager.GetBookingByBookingNo(r.BookingNo);
                        r.CheckOut = System.DateTime.Now;
                        r.RoomStatus = "Vacant";
                        r.BookingNo = 0;

                        housekeepingOscar h = HousekeepingDBManager.GetRoomByRoomNo(r.RoomNo);
                        h.roomStatus = r.RoomStatus;
                        h.roomType = r.RoomType;
                        HousekeepingDBManager.UpdateHousekeeping(h);

                        if (RoomDBManager.updateRooms(r))
                        {
                            CheckOutBtn.Enabled = false;
                            RePrint.Visible = true;

                            DetailsForm details = new DetailsForm(b, r, i);
                            details.Text = "Check Out Details";
                            details.ShowDialog();
                        }
                        else
                        {
                            InvoiceDBManager.DeleteBookingByInvoiceId(InvoiceId);
                            MessageBox.Show("Room Update Fail!");
                        }

                    }
                    else
                    {
                        MessageBox.Show("Fail to generate invoice.");
                    }
                }
            }
            //This is to catch all types of exception that is not handled by the if else. 
            //Also to ensure the application is still running.
            catch (Exception ex)
            {
                MessageBox.Show("A serious error has occured during checkout process.");
            }
        }

        private void PickRooms_Click(object sender, EventArgs e)
        {
            RoomInfo room = new RoomInfo(setData, "Occupied");
            room.Owner = this;
            room.ShowDialog();
        }

        private void setData(Rooms r)
        {
            if (r == null)
            {
                RoomNo.Text = "";
            }
            else
            {
                RoomNo.Text = r.RoomNo.ToString();
                i.BookingNo = r.BookingNo;
                i.RoomNo = r.RoomNo;
                i.RoomType = r.RoomType;
                i.RoomRates = r.RoomRates;
                i.CheckIn = r.CheckIn;
                r.CheckOut = System.DateTime.Now;
                i.CheckOut = r.CheckOut;
                i.CurrencyRates = 1;

                RoomRates.Text = "$ " + i.RoomRates;
                CurrencyRates.Text = i.CurrencyRates.ToString();
                DayNo.Text = i.getNumberOfDays().ToString();
                SGDTotal.Text = "$ " + i.calculateTotal().ToString();
                FinalTotal.Text = "$ " + i.calculateTotalToCurrency().ToString();
            }
            //to reset the new room data & validation
            this.r = r;
            CheckOutBtn.Visible = true;
            RePrint.Visible = false;
            isValid = true;
        }

        private void CreditCardCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (CreditCardCheckBox.Checked)
            {
                CreditCardGroupBox.Visible = true;
            }
            else
            {
                CreditCardGroupBox.Visible = false;
            }
            CreditCardNo.Text = "";
            SecurityCode.Text = "";
            CardType.Text = "";
            this.Refresh();
        }

        private void RoomNo_TextChanged(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(RoomNo.Text))
            {
                PaymentDetailsGroupBox.Visible = false;
                CreditCardGroupBox.Visible = false;
                CalculationGroupBox.Visible = false;
            }
            else
            {
                PaymentDetailsGroupBox.Visible = true;
                CalculationGroupBox.Visible = true;
                CheckOutBtn.Visible = true;
            }
            this.Refresh();
        }

        private void CurrencyRatesTb_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(CurrencyRatesTb.Text))
            {
                Double currencyRates = Convert.ToDouble(CurrencyRatesTb.Text);
                if (Regex.IsMatch(currencyRates.ToString(), @"(\d+.\d{2})|\d"))
                {
                    i.CurrencyRates = currencyRates;
                }
                else
                {
                    i.CurrencyRates = 0;
                }
            }
            else
            {
                i.CurrencyRates = 0;
            }
            CurrencyRates.Text = i.CurrencyRates.ToString();
            FinalTotal.Text = "$ " + i.calculateTotalToCurrency().ToString();
        }

        private void RePrint_Click(object sender, EventArgs e)
        {
            DetailsForm details = new DetailsForm(b, r, i);
            details.Text = "Check Out Details";
            details.ShowDialog();
        }

        private void CustomValidateForCreditCard()
        {
            foreach (Control ctrl in CreditCardGroupBox.Controls)
            {
                TextBox tb = ctrl as TextBox;
                if (tb != null)
                {
                    if (String.IsNullOrEmpty(tb.Text))
                    {
                        isValid = false;
                        errorProvider.SetError(tb, "The field is empty!");
                    }
                    else if (tb.Name == "SecurityCode" && !Regex.IsMatch(tb.Text, @"^\d+$"))
                    {
                        isValid = false;
                        errorProvider.SetError(tb, "The security code is not in numeric format!");
                    }
                }
            }
        }
    }
}
